$(document).ready(function() {
    scrollToTop();
	changeWatchList();
	showUserOption();
	checkChangeNewPass();
	animationManageTab();
	if (loadCalendar) {
		$.datepicker.setDefaults({
			dateFormat: 'dd-M-yy',
			changeMonth: true,
			changeYear: true,
			maxDate: new Date(),
			minDate: new Date(2005, 1, 1),
			showButtonPanel: true
		});
		$("#startdate, #enddate").datepicker();
	}
    
    $('table.table-data').bind('scroll', function(){
        alert('0');
    });
});

function scrollToTop(){
    $(window).scroll(function(){
		if ($(this).scrollTop() > 100) {
			$('.scrollup').fadeIn();
		} else {
			$('.scrollup').fadeOut();
		}
	}); 
	
	$('.scrollup').click(function(){
		$("html, body").animate({ scrollTop: 0 }, 600);
		return false;
	});
}

function redirect(url) {
	window.location = url;
}

function deleteSymbol(val, key) {
	$('p.message').html("");
	var conf = confirm("This will delete symbol " + key + ". Are you sure ?");
	if (conf) {
		loadingToggle(true);
		$.ajax({
			url: $("#deletesymbolurl").val(),
			method: "POST",
			data: "id=" + val,
			success: function(ret) {
				if (ret > 0) {
					$.ajax({
						url: $("#symbolslisturl").val(),
						type: "GET",
						cache: false,
						success: function(data2) {
							$("p.message").html("<span class='success'>Symbol " + key + " was deleted !</span>");
							$("#symbolslist").html(data2);
						}
					}).done(function() {
						loadingToggle(false);
					});
				} else {
					$('p.message').html("<span class='error'>Symbol " + key + " has data, can not be deteted !</span>");
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				$('p.message').html("<span class='error'>Symbol " + key + " has data, can not be deteted !</span>");
				loadingToggle(false);
			}
		});
	}
}

function doExplore(geturl) {
	$('p.message').html("");
	if ($('select#watchlist').val() == -1) {
		return;
	}
	if (isNaN($('input#sdmean').val()) || $('input#sdmean').val() == 0) {
		$('p.message').html("<span class='error'><strong>SD-MEAN</strong> must be a number and it can not equal 0.</span>");
		$('input#sdmean').focus();
		return;
	}
	loadingToggle(true);
	$.ajax({
		url: geturl,
		data: $('#frmexplore').serialize(),
		type: "POST",
		success: function(data) {
			if (data == "") {
				$('p.message').html("<span class='error'>No record found.</span>");
			} else{
                $('div#exploration-result').html(data); 
			}
			loadingToggle(false);
		}
	}).done(function() {
		loadingToggle(false);
	});
}

function hideSymbol() {
	var but = $("button#hideshow");
	if (but.attr('data-state') == 'show') {
		but.attr('data-state', 'hide').text('Less');
	} else {
		but.attr('data-state', 'show').text('More');
	}
	$("div.hiddenPanel").slideToggle();
}

function showMore(divClass) {
	var but = $('button#showmore');
	if (but.text() == "More") {
		but.text('Less');
	} else {
		but.text('More');
	}
	$(divClass).slideToggle();
}

function loadingToggle(show) {
	if (show == true) {
		var w = $(window).width();
		var h = $(document).height();
		$("div#modal").css({
			"width": w,
			"height": h
		}).fadeIn();
	} else {
		$("div#modal").fadeOut();
	}
}

function getCompareData(url) {
	$("p.message").html("");
	if ($('select#cbxcmpa').val() == -1 || $('select#cbxcmpb').val() == -1) {
		$("p.message").html("<span class='error'><strong>Banks</strong> was invalid !</span>");
		return;
	} else {
		if ($('select#cbxcmpa').val() == $('select#cbxcmpb').val()) {
			$("p.message").html("<span class='error'><strong>Banks</strong> were the same !</span>");
			return;
		}
	}
	loadingToggle(true);
	$.ajax({
		url: url,
		type: "POST",
		data: $("form#frmhome").serialize(),
		cache: false,
		success: function(data) {
			$("div#table-compare").html(data);
			loadingToggle(false);
		},
		error: function(xhr, ajaxOptions, thrownError) {
			$("p.message").html("<span class='error'>Search keys were not invalid !</span>");
			loadingToggle(false);
		}
	});
}

function addSymbols(url) {
	$('p.message').html("");
	var sym = $("#txtnewsymbol").val().trim();
	if (sym == "") {
		$('p.message').html("<span class='error'><strong>Symbol</strong> can not be blank.</span>");
		$("#txtnewsymbol").val("");
		return;
	}
	loadingToggle(true);
	$.ajax({
		url: url,
		type: "POST",
		data: $('#frmsymbol').serialize(),
		cache: false,
		success: function(data) {
			$.ajax({
				url: $("#symbolslisturl").val(),
				type: "GET",
				cache: false,
				success: function(data2) {
					$("#txtnewsymbol").val("");
					$("p.message").html(data);
					$("#symbolslist").html(data2);
				}
			}).done(function() {
				loadingToggle(false);
			});
		}
	});
}

function getSymbolsData(url) {
	$('p.message').html("");
	var checkedCheckboxs = $('.symbolcheckbox:checked');
	if (checkedCheckboxs.length < 1) {
		$('p.message').append("<span class='error'>No symbol choosen !</span>");
		return;
	}
	var count = 0;
	var total = 0;
	var progressLabel = $(".progress-label");
	var progressbar = $("#progressbar");
	var symbolError = "";
	progressLabel.show();
	progressbar.progressbar({
		value: count,
		max: checkedCheckboxs.length,
		complete: function() {
			progressLabel.text("Complete!");
		}
	}).show();
	$.each(checkedCheckboxs, function(index) {
		var symbol = $(this).val();
		$.ajax({
			url: url,
			type: "POST",
			data: {
				val: symbol,
				startdate: $('#startdate').val(),
				enddate: $('#enddate').val()
			},
			cache: false,
			success: function(data) {
				total += 1;
				if (data > 0) {
					count += 1;
					progressbar.progressbar({
						value: count,
						change: function() {
							progressLabel.text($(this).progressbar("value") + "/" + $(this).progressbar("option", "max"));
						}
					});
					if(checkedCheckboxs.length == total){
						$('p.message').html("<span class='success'>Get data successful !</span>");
						$(".progress-label").text("Complete!");
					}
				} else {
					if(symbolError != ""){
						symbolError += ', ';
					}
					symbolError += symbol;
				}
				if(checkedCheckboxs.length == total && symbolError.length > 0){
					displayProgressbarError(symbolError);
				}
			}, error:function(data){
				total += 1;
				if(symbolError != ""){
					symbolError += ', ';
				}
				symbolError += symbol;
				if(checkedCheckboxs.length == total && symbolError.length > 0){
					displayProgressbarError(symbolError);
				}
			}
		});
	});
}

function displayProgressbarError(symbolError){
	$('p.message').html("<span class='error'>Symbol data of <strong>" + symbolError + '</strong> not found !</span>');
	$(".progress-label").text("Complete!");
}

function toggleCheckSymbol() {
	if ($("#checkall").is(":checked")) {
		$(".symbolcheckbox").prop('checked', true);
	} else {
		$(".symbolcheckbox").prop('checked', false);
	}
}

function changeWatchList() {
	$("select#watchlist").change(function() {
		if ($(this).val() != -1) {
			loadingToggle(true);
			$.ajax({
				url: $("#watchlist_url").val(),
				type: "POST",
				data: 'id=' + $(this).val(),
				success: function(data) {
					$('div#watchlist-details').html(data);
					loadingToggle(false);
				}
			});
		} else {
			$("div#watchlist-details select").val(-1);
			$("input#sdmean").val(0);
		}
	});
}

function addWatchList(url, url2) {
	$("p.message").html("");
	var watchlistname = $('#watchlistname').val();
	watchlistname = watchlistname.trim();
	if (watchlistname != null && watchlistname.length > 0) {} else {
		$("p.message").html("<span class='error'>Watchlist name invalid !</span>");
		$('#watchlistname').focus();
		return;
	}
	loadingToggle(true);
	$.ajax({
		url: url,
		type: "POST",
		data: $("#frmaddwatchlist").serialize() + '&watchlistname=' + $('input#watchlistname').val(),
		cache: false,
		success: function(data) {
			$.ajax({
				url: url2,
				type: "GET",
				cache: false,
				success: function(data2) {
					$("p.message").html(data);
					$("div#watchlist-list").find("p.list-row").remove();
					$("div#watchlist-list").html(data2);
					loadingToggle(false);
				}
			});
		}
	});
}

function calculateWatchList(url) {
	$("p.message").html("");
	loadingToggle(true);
	$.ajax({
		url: url,
		type: "POST",
		data: "id=" + $("#cbxwatchlist").val(),
		cache: false,
		success: function(data) {
			$("div#watchlist-result").html(data).slideDown();
			loadingToggle(false);
		}
	});
}

function cancelUpdate() {
	$("button#btnadd").show();
	$("button#btnupdate").hide();
	$("button#btncancelupdate").hide();
	$("input#watchlistname").val("");
	$("p.table-row select").val(-1);
}

function updateWatchlist(url, id, name) {
	$("p.message").html("");
	loadingToggle(true);
	$.ajax({
		url: url,
		type: "POST",
		data: 'id=' + id,
		cache: false,
		success: function(data) {
			$("input#watchlistname").val(name);
			$("button#btnadd").hide();
			$("button#btnupdate").show();
			$("button#btnupdate").attr('data-id', id);
			$("button#btncancelupdate").show();
			$("form#frmaddwatchlist").find("p.table-row").remove();
			$("form#frmaddwatchlist").append(data);
			loadingToggle(false);
		}
	});
}

function deleteWatchlist(url, id, rowid) {
	$("p.message").html("");
	var conf = confirm("Do you really want to remove this watch list ?");
	if (conf) {
		loadingToggle(true);
		$.ajax({
			url: url,
			type: "POST",
			data: 'id=' + id,
			cache: false,
			success: function(data) {
				$("p.message").html(data);
				$('p#' + rowid).remove();
				loadingToggle(false);
			},
			error: function(xhr, ajaxOptions, thrownError) {
				$("p.message").html("<span class='error'>List can not be deleted.Please try again !</span>");
				loadingToggle(false);
			}
		});
	}
}

function doUpdateWatchList(url, url2) {
	$("p.message").html("");
	var watchlistname = $('#watchlistname').val();
	watchlistname = watchlistname.trim();
	if (watchlistname != null && watchlistname.length > 0) {} else {
		$("p.message").html("<span class='error'>Watchlist name invalid !</span>");
		$('#watchlistname').focus();
		return;
	}
	loadingToggle(true);
	$.ajax({
		url: url,
		type: "POST",
		data: $("#frmaddwatchlist").serialize() + 
                '&id=' + $("button#btnupdate").attr('data-id') + 
                '&watchlistname=' + $('input#watchlistname').val(),
		cache: false,
		success: function(data) {
			$.ajax({
				url: url2,
				type: "GET",
				cache: false,
				success: function(data2) {
					$("p.message").html(data);
					$("div#watchlist-list").find("p.list-row").remove();
					$("div#watchlist-list").html(data2);
					loadingToggle(false);
				}
			});
		}
	});
}
var timeOut = null;

function showUserOption() {
	$("p#user-option").bind('mouseover', function() {
		$("div#usertop-option").fadeIn('fast');
		timeOut = setTimeout(function() {
			$("div#usertop-option").fadeOut('fast');
		}, 3000);
	});
	$("div#usertop-option").mouseenter(function() {
		clearTimeout(timeOut);
		$("div#usertop-option").unbind('fadeOut').fadeIn();
	}).mouseleave(function() {
		$("div#usertop-option").fadeOut('fast');
	});
}

function checkChangeNewPass() {
	$("#chknewpass").click(function() {
		if ($(this).prop('checked')) {
			$('input#newpassword').removeAttr('disabled');
		} else {
			$('input#newpassword').attr('disabled', 'disabled');
		}
		$('p#newpassword-confirm').slideToggle();
	});
}

function animationManageTab() {
	$("div.row p#tab-nav span.tab-title").click(function() {
		var left = $(this).attr('data-left');
		$("p.message").html("");
		$("div#tab-wrap-content").animate({
			scrollLeft: left
		}, 600);
		$("div.row p#tab-nav span.tab-title").removeClass('selected');
		$(this).addClass('selected');
	});
}

function doBackTest(url){
	loadingToggle(true);
	$('p.message').html('');
	$.ajax({
		url:url,
		type:'POST',
		cache:false,
		data:$('#frmBackTest').serialize(),
		success:function(data){
			$('div#table-backtest').html(data);
			loadingToggle(false);
		}
	});
}

function toggleShowTradeList(){
	$('div#trade-list').slideToggle();
	return false;
}